
package info.niwota.frames;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

/**
 * @author qiangli
 * 
 */
public class ScreenActivity extends Activity {

	private class MyGestureListener extends
			GestureDetector.SimpleOnGestureListener {

		@Override
		public boolean onDoubleTap(MotionEvent e) {
			doTap2();
			return true;
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {

			try {
				float dx12 = (e1.getX() - e2.getX());
				float dx21 = (e2.getX() - e1.getX());
				float dy12 = (e1.getY() - e2.getY());
				float dy21 = (e2.getY() - e1.getY());

				float dd = (Math.abs(dx12) - Math.abs(dy12));

				if (dd > 0) {
					// left right
					if (dx12 > SWIPE_MIN_X_DISTANCE
							&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
						doSwipeLeft();
					} else if (dx21 > SWIPE_MIN_X_DISTANCE
							&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
						doSwipeRight();
					}
				} else {
					// up down
					if (dy12 > SWIPE_MIN_Y_DISTANCE
							&& Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
						doSwipeUp();
					} else if (dy21 > SWIPE_MIN_Y_DISTANCE
							&& Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
						doSwipeDown();
					}
				}
			} catch (Exception e) {
				// nothing
			}

			return true;
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			doTap();
			return true;
		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			return true;
		}
	}

	private class RefreshHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			_fadeout();
		}

		public void sleep(long delay) {
			this.removeMessages(0);
			sendMessageDelayed(obtainMessage(0), delay);
		}
	}

	private static final float SWIPE_MIN_X_DISTANCE = 120;

	private static final float SWIPE_MIN_Y_DISTANCE = 80;

	private static final int SWIPE_THRESHOLD_VELOCITY = 180; // 200

	private static final String TAG = "ScreenActivity";

	private float current;

	private GestureDetector gestureDetector;

	private RefreshHandler handler = new RefreshHandler();

	private PowerManager.WakeLock wakeLock;

	private void _fadeout() {
		if (Debug.DEBUG) {
			Log.d(TAG, "fadeout " + current);
		}
		try {
			current -= 0.10f;
			if (current > Screens.MIN_SCREEN_BRIGHTNESS) {
				handler.sleep(100);
				Screens.setBrightness(this, current);
			} else {
				Screens.blackout(this);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void acquireLock() {
		if (Debug.DEBUG) {
			Log.v(TAG, "Acquiring wake lock");
		}
		if (wakeLock != null) {
			wakeLock.acquire();
			return;
		}
		try {
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
			wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
			wakeLock.acquire();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void dim() {
		current = Screens.FULL_SCREEN_BRIGHTNESS;
		_fadeout();
	}

	public void doSwipeDown() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doSwipeDown");
		}
	}

	public void doSwipeLeft() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doSwipeLeft");
		}
	}

	public void doSwipeRight() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doSwipeRight");
		}
	}

	public void doSwipeUp() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doSwipeUp");
		}
	}

	public void doTap() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doTap");
		}
		dim();
	}

	public void doTap2() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doTap2 double tap");
		}
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onActivityResult requestCode " + requestCode
					+ " resultCode: " + resultCode + " data: " + data);
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onConfigurationChanged " + newConfig);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onCreate " + savedInstanceState);
		}
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.screen);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		//
		gestureDetector = new GestureDetector(this, new MyGestureListener());
		//View screen = findViewById(R.id.screen);
		//TextView ind = (TextView) findViewById(R.id.screen_indicator);
		//ind.setText(R.string.app_name);
		//
		dim();
	}

	@Override
	protected void onDestroy() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onDestroy");
		}
		super.onDestroy();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onKeyDown " + keyCode + " event: " + event);
		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onNewIntent " + intent);
		}
	}

	@Override
	protected void onPause() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onPause");
		}
		super.onPause();
		//
		releaseLock();
	}

	@Override
	protected void onResume() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onResume");
		}
		//
		super.onResume();
		//
		acquireLock();
	}

	@Override
	protected void onStart() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onStart ");
		}
		super.onStart();
		//
	}

	@Override
	protected void onStop() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onStop ");
		}
		super.onStop();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// if (Debug.DEBUG) {
		// Log.d(TAG, "onTouchEvent " + event);
		// }
		if (gestureDetector != null) {
			gestureDetector.onTouchEvent(event);
		}
		return true;
	};

	private void releaseLock() {
		if (Debug.DEBUG) {
			Log.v(TAG, "Releasing wake lock");
		}
		if (wakeLock != null) {
			wakeLock.release();
			wakeLock = null;
		}
	}

}
